package com.zipking.cloud.springbootmybatis.current;

import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DataProcessingPipeline {
    private final ExecutorService executor = Executors.newFixedThreadPool(4);
    private final CyclicBarrier barrier;
    private final int numberOfPhases;
    private final int numberOfTasks;

    public DataProcessingPipeline(int numberOfTasks, int numberOfPhases) {
        this.numberOfTasks = numberOfTasks;
        this.numberOfPhases = numberOfPhases;
        this.barrier = new CyclicBarrier(numberOfTasks, () -> {
            System.out.println("一个阶段完成，准备进入下一阶段");
        });
    }

    public void processData() throws Exception {
        for (int phase = 1; phase <= numberOfPhases; phase++) {
            System.out.println("阶段 " + phase + " 开始");
            for (int task = 0; task < numberOfTasks; task++) {
                final int currentTask = task;
                int finalPhase = phase;
                executor.submit(() -> {
                    try {
                        // 数据处理任务
                        System.out.println("任务 " + currentTask + " 在阶段 " + finalPhase + " 执行");
                        Thread.sleep((long) (Math.random() * 5000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            barrier.await();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            barrier.await(); // 等待所有任务完成
        }
        executor.shutdown();
    }

    public static void main(String[] args) {
        DataProcessingPipeline pipeline = new DataProcessingPipeline(4, 3);
        try {
            pipeline.processData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
